let productsData=require('../../data/products.js');
const app = getApp()
let _self;
Page({
  data: {
    deskId:'1',
    currentId:'0',
    currentProductId:0,
    carts:[],
    isBottom:false,
    imageUrls: [],
    products:[],
    tempProducts:[],
    types:[]
  },
  onShow:function(){
    let temp=this.data.products;
    this.data.carts=app.globalData.carts;
    this.setData({tempProducts:temp});
    wx.setTabBarBadge({
      index: 1,
      text: this.data.carts.length.toString(),
    })
  },
  onLoad: function() {
    
    this.setData({ 
      imageUrls: productsData.imageUrls,
      products:productsData.products,
      types:productsData.types
    });
  },
  getDeskId:function(){
    _self=this;
    wx.scanCode({
      onlyFromCamera:true,
      success:res=>{
        if(res.result!=null){
          let id=res.result.split('=')[1];
          _self.setData({deskId:id});
          app.globalData.deskId=id;
        }
      },
      fail:error=>console.log(error)
    });
  },
  switchTab:function(event){
    _self = this;
    let tabId=event.currentTarget.dataset.tabId;
    let tempArrays;
    if(tabId==0){
      tempArrays=_self.data.products;
    }else{
      tempArrays = _self.data.products.filter(element => element.typeId == tabId);
    }
    _self.setData({ currentId: tabId, tempProducts:tempArrays});
  },
  addCarts:function(event){
    let productId=event.currentTarget.dataset.id;     //获取商品id
    let product=this.data.products.find(element=>element.id==productId);  //根据id获取商品数据
    //检测购物车中是否已经存在某个商品
    if(this.data.carts.includes(product)){
      this.data.carts.find(element=>element.id==productId).count++;   //不添加商品，直接数量加1
    }else{
      this.data.carts.push(product);    //添加商品
    }
    app.globalData.carts=this.data.carts;
    wx.setTabBarBadge({
      index: 1,
      text: this.data.carts.length.toString(),
    })
  },
  toDetail:function(event){
    let cpi=event.currentTarget.dataset.pid;
    this.setData({currentProductId:cpi});
    wx.navigateTo({
      url: '/pages/detail/detail',
    })
  },
  onReachBottom: function () {
    _self=this;
    _self.setData({isBottom:true});
    setTimeout(function () {
      _self.setData({ isBottom: false });
    }, 2000);
  }
})
